package com.lglin.service.product.Impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.lglin.bean.product.entity.Category;
import com.lglin.bean.product.entity.Product;
import com.lglin.common.bean.Review;
import com.lglin.common.constant.Constant;
import com.lglin.common.utils.other.CommonUtil;
import com.lglin.dao.product.ProductDao;
import com.lglin.service.product.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class ProductServiceImpl implements ProductService {
    @Autowired
    private ProductDao productDao;

    @Override
    public List<Category> getCategory() {
        return productDao.getCategory();
    }

    @Override
    public int getProductCountBycId(int cId, String key) {
        return productDao.getCountBycId(cId, key);
    }

    @Override
    public List<Product> selectProducts(String data) {
        JSONObject jsonObject = JSONObject.parseObject(data);
        int pageNum = jsonObject.getInteger("pageNum");
        int sort_flag = jsonObject.getInteger("sort_flag");
        String key = jsonObject.getString("key");
        //判断是否有分类条件查询如过没有条件查询
        if (jsonObject.getString("id_arr").equals("[]")) {
            PageHelper.startPage(pageNum, Constant.PageSize);
            return productDao.selectAll(sort_flag, key);
        }
        //如果存在分类去查询对应的PID组成一个数组，如果分类没有对应的PID就直接返回空
        int[] idArray = CommonUtil.splitData(data);
        List<Integer> pIds = productDao.selectBycId(idArray);
        if (pIds.isEmpty()) {
            return null;
        }
        //存在分类对应的PID继续查询对应PID信息然后返回
        List<Integer> newPIds = CommonUtil.removeDuplicate(pIds);
        PageHelper.startPage(pageNum, Constant.PageSize);
        return productDao.selectById(newPIds, sort_flag, key);
    }

    @Override
    public Product selectOneById(int id) {
        return productDao.selectOneById(id);
    }

    @Override
    public int getReviewsCountById(int id) {
        return productDao.getReviewsCountById(id);
    }

    @Override
    public List<Review> getReviewsById(int id) {
        return productDao.getReviewsById(id);
    }

    @Override
    public List<Integer> getAllStarById(int id) {
        return productDao.getAllStarById(id);
    }

    @Override
    public List<Product> selectProductsByIds(List<Integer> list) {
        return productDao.selectById(list, 0, "");
    }

    @Override
    public List<Map<String, Object>> recomProduct(int num) {
        return productDao.recomProduct(num);
    }
}
